package com.company;

/**
 * @author zhf
 * @date 2021/11/16
 */
public class MinPathNum {
    public static void main(String[] args) {
        //{1,3,1},{1,5,1},{4,2,1}
        int[][] grid = new int[][]{{1,3,1},{1,5,1},{4,2,1}};
        MinPathNum pathNum = new MinPathNum();
        int ans = pathNum.minPathSum(grid);
        System.out.println(ans);
    }


    /*
    动态规划
     */
    public int minPathSum(int[][] grid) {
        int wight = grid.length;
        int hight = grid[0].length;

        int dp[][] = new int[wight][hight];
        dp[0][0] = grid[0][0];
        /*
        数组为空返回0；
         */
        if (hight == 0 || wight == 0) {
            return 0;
        }

        for (int i = 1; i < wight; i++) {
            dp[i][0] = dp[i - 1][0] + grid[i][0];
        }

        for (int i = 1; i < hight; i++) {
            dp[0][i] = dp[0][i - 1] + grid[0][i];
        }

        for (int i = 1; i < wight; i++) {
            for (int j = 1; j < hight; j++){
                dp[i][j] = Math.min(dp[i][j - 1],dp[i - 1][j]) + grid[i][j];
            }

        }
        return dp[wight - 1][hight - 1];

    }
}
